package ch1.threadlocal;

public class UseThreadLocal {
    //变量1
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    //变量2
    private static ThreadLocal<String> stringThreadLocal;

    /**
     * 方法1，运行3个线程
     */
    private void StartThreadArray() {
        Thread[] runs = new Thread[3];
        for (int i = 0; i < runs.length; i++) {
            runs[i] = new Thread(new TestThread(i));
        }
        for (Thread run : runs) {
            run.start();
        }
    }

    /**
     * 定义线程，线程的工作是将ThreadLocal变量的值变化，并写回，看看线程之间是否会互相影响
     */
    public static class TestThread implements Runnable {
        int id;

        TestThread(int id) {
            this.id = id;
        }

        public void run() {
            System.out.println(Thread.currentThread().getName() + ":start" + " id=" + id);
            Integer s = threadLocal.get();
//            s = s + id;  //三个线程传进来的id分别为0  1   2  原始值是5  所以打印出来的
            threadLocal.set(s+1);
            System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
            //intLocal.remove();
        }
    }

    public static void main(String[] args) {
        UseThreadLocal useThreadLocal = new UseThreadLocal();
        useThreadLocal.StartThreadArray();
    }
}